app.controller('personalinformationscontroller', ['$scope', '$parse', '$http', '$rootScope', function($scope, $parse, $http, $rootScope)
{
	$scope.loadingPersonalInformations = true;
	
	$scope.$on('translations', function(event, args) {
		$scope.translations = args.translations.response;
	});
	
	function convertToPascalCase() {
		return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
	}
	
	function convertToLower() {
		return this.toLowerCase(); 
	}

	String.prototype.toLower = convertToLower;
	String.prototype.toPascalCase = convertToPascalCase;

	/**
	* Update the event command
	*/
	$scope.updateUserCommand = function()
	{
		console.info("updateUserCommand - called"); 
		
		try
		{
			if($scope.editUserFirstname == "")
			{
				throw "Le prénom de l'utilisateur est obligatoire.";
			}
			
			if($scope.editUserLastname == "")
			{
				throw "Le nom de l'utilisateur est obligatoire.";
			}
			
			if($scope.editUserEmail == "")
			{
				throw "L'adresse mail de l'utilisateur est obligatoire.";
			}

			var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(re.test($scope.editUserEmail) == false)
			{
				throw "L'adresse mail de l'utilisateur n'est pas valide.";
			}
			
			if($scope.editUserLogin == "")
			{
				throw "L'identifiant de l'utilisateur est obligatoire.";
			}
			
			if($scope.editPassword != "" && $scope.editPassword != undefined)
			{
				$scope.updateUserPasswordCommand($scope.newPassword);
			}
			
			$http.post($scope.servicebase, { "service" : "updateUserInformations", "id" : $scope.currentUser.Id, "firstname" : $scope.editUserFirstname.toPascalCase(), "lastname" : $scope.editUserLastname.toPascalCase(), "company" : $scope.editUserCompany.toPascalCase(), "email" : $scope.editUserEmail.toLower(), "phonenumber" : $scope.editUserPhoneNumber, "webaddress" : $scope.editUserWebAddress.toLower(), "login" : $scope.editUserLogin}).
			success(function(data, status) 
			{
				console.info("updateUserCommand - call success"); 
				$scope.status = status;
				$scope.data = data;
				$scope.result = data; 
				$scope.personalInformationsMessageVisible = true;
				
				if(data.isFailed == true)
				{
					$scope.setMessageCommand($scope.data.exception, 'danger', 'personalInformationsMessage');
				}
				else
				{
					if($scope.avatar != undefined)
					{
						$scope.attachAvatarToUserCommand($scope.currentUser.Id);
					}
					
					$scope.setMessageCommand("Les informations ont été mise à jour." , 'success', 'personalInformationsMessage');
					
					$scope.currentUser.Firstname = data.response.Firstname;
					$scope.currentUser.Lastname = data.response.Lastname;
					$scope.currentUser.Email = data.response.Email;
					$scope.currentUser.Company = data.response.Company;
					$scope.currentUser.PhoneNumber = data.response.PhoneNumber;
					$scope.currentUser.WebAddress = data.response.WebAddress;
					$scope.currentUser.Login = data.response.Login;
				}
			})
			.
			error(function(data, status) 
			{
				console.error("updateUserCommand - call failed"); 	
				$scope.data = data || "Request failed";
				$scope.status = status;			
				console.error("updateUserCommand - data : " + $scope.data); 				
			});
		}
		catch(err) 
		{
			$scope.personalInformationsMessageVisible = true;
			$scope.setMessageCommand(err, 'danger', 'personalInformationsMessage');
		}
	};

	/**
	* Set an avatar on the event
	*/
	$scope.setAvatarCommand = function(file)
	{
		console.info("setAvatarCommand called ");

		var r = new FileReader();

		r.onload = function(e) 
		{ 
			var contents = e.target.result;
			$scope.previewAvatar = contents;
			$scope.avatar = file;
			$scope.editUserHasAvatar = true;
			$scope.attachAvatarToUserCommand($rootScope.currentUser.Id);
		}
		  
		r.readAsText(file);
	};
	
	/**
	* Attach a avatar on an user
	*/
	$scope.attachAvatarToUserCommand = function(idUser)
	{
		console.info("attachAvatarToUserCommand - called with id user : " + idUser);
		
		var fd = new FormData();
		fd.append("service", "attachAvatarOnAnUser");
		fd.append("idUser", idUser);
		fd.append("file", $scope.avatar);
		
		$http.post($scope.servicebase,
			fd,
			{ 
				withCredentials: true, headers: {'Content-Type': undefined }, transformRequest: angular.identity 
			}
		).
		success(function(data, status) 
		{
			console.info("attachAvatarToUserCommand - call success"); 
			$scope.personalInformationsMessageVisible = true;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand(data.exception, 'warning', 'personalInformationsMessage');
			}
			else
			{
				$scope.setMessageCommand('Avatar joint.', 'success', 'personalInformationsMessage');
				$rootScope.setCurrentUser(data.response);
			}
			$scope.avatar = undefined;
		})
		.
		error(function(data, status) 
		{
			console.error("attachAvatarToUserCommand - call failed"); 	
			$scope.setMessageCommand('Ajout d\'une affiche en échec.', 'danger');
			$scope.data = data || "Request failed";
			$scope.status = status;				
			console.error("attachAvatarToUserCommand - data : " + $scope.data);			
		});
	};
	
	/**
	* Set a new password for the user
	*/
	$scope.updateUserPasswordCommand = function(newPassword)
	{
		console.info("updateUserPasswordCommand - called"); 
		$http.post($scope.servicebase, { "service" : "updateUserPassword", "id" : $scope.currentUser.Id, "newPassword" : newPassword}).
		success(function(data, status) 
		{
			console.info("updateUserPasswordCommand - call success"); 
			$scope.status = status;
			$scope.data = data;
			$scope.result = data; 
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger', 'personalInformationsMessage');
			}
			else
			{
				$scope.messageUpdateUserVisible = true;
				$scope.setMessageCommand('Mot de passe mis à jour', 'warning', 'personalInformationsMessage');
			}
		})
		.
		error(function(data, status) 
		{
			console.error("updateUserPasswordCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.status = status;			
			console.error("updateUserPasswordCommand - data : " + $scope.data); 				
		});
	};
	
	/**
	*	Load the personal information component
	*/
	$scope.loadPersonalInformationsComponentCommand = function() 
	{
		console.info("loadPersonalInformationsComponentCommand - called");
		$scope.profiles = '';
		$scope.previewAvatar = undefined;
		$scope.avatar = undefined;
		$scope.loadingPersonalInformations = false;
		
		$scope.editUserFirstname = $scope.currentUser.Firstname;
		$scope.editUserLastname = $scope.currentUser.Lastname;
		$scope.editUserEmail = $scope.currentUser.Email;
		$scope.editUserCompany = $scope.currentUser.Company;
		$scope.editUserPhoneNumber = $scope.currentUser.PhoneNumber;
		$scope.editUserWebAddress = $scope.currentUser.WebAddress;
		$scope.editUserLogin = $scope.currentUser.Login;
	};
	
	$scope.loadPersonalInformationsComponentCommand();
}]);